--
-- Author: shunguo.chen
-- Date: 2018-08-11 16:54:22
--
-- 客户端的gm密令

local function sendGMCommand(text)
    print("sendGMCommand", text)
    app:sendMsg("IMModel", "sendSystemMessage", text)
end

if DEBUG > 0 then
    -- add custom command
    app:addCommand("snapshot", function(text)
        local ary = string.split(text, " ")
        if #ary > 1 then
            debug.luaSnapshot(ary[#ary])
        else
            debug.luaSnapshot(nil)
        end
    end)

    app:addCommand("restart", function(text)
        local dialog = display.newMessageBox(L("lua_code_text_9"),function()
            app:relaunchApp()
        end)
        UIHandler:addPopDialog(dialog)
    end)

    app:addCommand("play", function(text)
        local ary = string.split(text, " ")
        local character = FieldManager:getMyCharacter()
        -- character:play(ary[2])
        character:showBubble(L(ary[2]), 2)
    end)

    app:addCommand("removeui", function(text)
        UIHandler:removeAllUI(true)
    end)

    app:addCommand("legend", function(text)
        for i=1, 9 do
            local id = 75000030 + i
            scheduler.newCron(function()
                if id >= 75000038 then
                    sendGMCommand(string.format("/additem %s 10", id))
                else
                    sendGMCommand(string.format("/additem %s 2000", id))
                end
            end, i * 3)
        end
    end)

    -- 游戏中重登录msdk
    app:addCommand("msdk", function(text)
        app.channelAPI:setLastWakeUpPlatform(app.channelAPI:getWGPlatform())
        app.session.clearLogined = function() end
        app.channelAPI:logout()
        app.channelAPI._isIgnoreWakeUpFrom = false
        app.channelAPI:showLoginView()
    end)

    -- 模拟服务器发消息
    app:addCommand("server", function(text)
        app.session.connecter:invokeHandlers("pb_server.S2C_ServerInfo", {clientVersion="2.1.1.1"})
    end)

    app:addCommand("close", function(text)
        local ary = string.split(text, " ")
        if ary[2] == "session" then
            app.session:disconnect(nil, false)
        elseif ary[2] == "battle" then
            BattleManager.mBattleController.model.connector:close(nil, false)
        end
    end)

    app:addCommand("dailyup", function(text)
        local ary = string.split(text, " ")
        EM:notify("onDailyUpdate", ary[2] == "1")
    end)

    app:addCommand("push", function(text)
        local ary = string.split(text, " ")
        local tp = tonumber(ary[2] or 0)
        if tp == 0 then
            app.channelAPI:deletePushData()
        else
            -- 一分钟之后触发
            local date = os.date("*t", os.time())
            dump(date, "push date")
            local time = date.hour*3600+ date.min*60 + date.sec + 60

            local params = {
                title = "推送标题 " .. tp,
                msg = "这是推送内容，随便看看就好，主要是要你回游戏来。类型 " .. tp,
                dataType = tp,
                time = time,
                UTC = 8,
                className = "org.cocos2dx.lua.AppActivity",
                pushType = 2,
            }
            dump(params, "push.params")
            app.channelAPI:savePushData(params)
        end
    end)

    app:addCommand("tm", function(text)
        local ary = string.split(text, " ")
        local params
        if #ary == 3 then
            params = {matchType=tonumber(ary[2]), targetType=tonumber(ary[3])}
        elseif #ary == 2 then
            params = {targetId=tonumber(ary[2])}
        end
        app:sendMsg("TeamMatchController", "openView", params)
    end)

    app:addCommand("init", function(text)
        local ary = string.split(text, " ")
        if ary[2] == "mount" then
            -- 添加所有非金腰带坐骑，有灵魂石的+1000灵魂石
            local confs = GD:getMountConfigs()
            local soulIds = {}
            local idx, max = 0, #confs
            local conf
            local mountCron = scheduler.newCron(function()
                idx = idx + 1
                if idx <= max then
                    conf = confs[idx]
                    if conf.enable == "1" and conf.type2 == "0" then
                        sendGMCommand("/addmount " .. conf.ID)
                        if conf.soulID then
                            soulIds[#soulIds + 1] = conf.soulID
                        end
                    end
                elseif idx <= (max + #soulIds) then
                    sendGMCommand("/add 80 " .. soulIds[idx-max] .. " " .. 500)
                else
                    scheduler.cancelCron(mountCron)
                end
            end, 2, true)
        end
    end)

    -- 显示隐藏快捷使用界面
    app:addCommand("quickuse", function(text)
        local ary = string.split(text, " ")
        if ary[2] == "0" then
            app:sendMsg("UIController", "hideQuickView")
        else
            app:sendMsg("UIController", "showQuickView")
        end
    end)

    app:addCommand("tcptick", function(text)
        local ary = string.split(text, " ")
        TCP_TICK_ENABLE = tonumber(ary[2]) == 1
    end)

    app:addCommand("monitor", function(text)
        collectgarbage("collect")
        collectgarbage("collect")
        collectgarbage("collect")
        local ary = string.split(text, " ")
        if #ary > 1 then
            if ary[2] == "sortbykey" then
                debug.dumpMonitor(nil, ary[2])
            else
                debug.dumpMonitor(ary[2])
            end
        else
            debug.dumpMonitor()
        end
    end)

    app:addCommand("memcache", function(text)
        local args = string.split(text, " ")
        if #args > 1 then
            if args[2] == "start" then
                debug.startMemCache()
            elseif args[2] == "diff" then
                debug.diffMemCache()
            end
        end
    end)

    app:addCommand("func", function(text)
        local ary = string.split(text, " ")
        if ary[2] == "1" then
            UIHandler:addOpenFunctionId(tonumber(ary[3]))
        else
            UIHandler:removeOpenFunctionId(tonumber(ary[3]))
        end
    end)

    app:addCommand("guide", function(text)
        local ary = string.split(text, " ")
        app:sendMsg("GuideModel", "testGuide", tonumber(ary[2] or 0))
        app:sendMsg("IMRoomController", "hideView")
    end)

    app:addCommand("feature", function(text)
        local ary = string.split(text, " ")
        local funcId = tonumber(ary[2] or 0)
        EM:notify("onFunctionOpen", funcId)
        -- local desktopCtl = UIHandler:getDesktopController()
        -- if desktopCtl and funcId > 0 then
        --     desktopCtl.mDesktopModel:addFunctionId(funcId, true)
        --     desktopCtl:refreshNewFunction(true)

        --     if funcId == 10030 then
        --         app:sendMsg("GuideModel", "testGuide", 138)
        --     end
        -- end
    end)

    app:addCommand("preview", function(text)
        local ary = string.split(text, " ")
        local tp = tonumber(ary[2] or 1)
        local id = tonumber(ary[3] or 11)
        local params = {type=tp, id=id}
        app:sendMsg("PlayerController", "openAvatarPreView", params)
    end)

    app:addCommand("dumptexture", function()
        local path = app:getTempFolder().."/texture_warnning.txt"
        local infos = TextureCache:getCachedTextureInfo()
        FileUtils:writeStringToFile(infos, path, function(ret)
            display.pushToast("dumptexture success")
        end)
    end)

    app:addCommand("pay", function()
        local ary = string.split(text, " ")
        local num = tonumber(ary[2] or 1)
        local params = {count=num, productId="com.tencent.wjyz_diamond_60"}
        app.channelAPI:pay(function(ret)
            print("app.channelAPI:pay ret = " .. tostring(ret))
            if ret == Enums.PayRetState.success then
                app.session:request("tencent.C2S_CheckRecharge", {}, function(ret)
                    dump(ret, "tencent.C2S_CheckRecharge")
                    if ret.ok then
                        display.pushToast(L("recharge_succ"))
                    end
                end)
            else

            end
        end, params)
    end)

    app:addCommand("checkpay", function()
        print("tencent.C2S_CheckRecharge")
        app.session:request("tencent.C2S_CheckRecharge", {}, function(ret)
            dump(ret, "tencent.C2S_CheckRecharge")
            if ret.ok then
                display.pushToast(L("recharge_succ"))
            end
        end)
    end)

    app:addCommand("showallnpc", function()
        NpcFactory:createAllMapBaseNpcWithoutLimit(MapManager:getMapId())
        NpcManager:allNpcAbslutelyVisibility(true)
    end)

    app:addCommand("/debug", function()
        local view = require("app.debuger.DebugPanel").new()
        Director:getRunningScene():addChild(view,9999)
        app:sendMsg("IMRoomController", "hideView")
    end)

    app:addCommand("/fps", function()
        Director:setDisplayStats(not Director:isDisplayStats())
    end)

    app:addCommand("/tb", function()
        BattleManager:SimulateBattle(0)
    end)

    app:addCommand("/immode", function(text)
        local ary = string.split(text, " ")
        if #ary > 1 then
            app:sendMsg("IMModel", "setMode", tonumber(ary[2]))
        end
    end)

    app:addCommand("/teststory", function(text)
        local ary = string.split(text, " ")
        if #ary > 1 then 
            DoEventHandler.testSimulationTaskStory(tonumber(ary[2]))
        end
    end)

    app:addCommand("/scalemin", function()
        MapManager:mapTouchZoomOut(1, 1)
    end)

    app:addCommand("/scalemax", function()
        MapManager:mapTouchZoomIn(1, 1)
    end)

    app:addCommand("/openchampion", function()
        app:sendMsg("PvpController", "setChampionForceOpen")
    end)

    app:addCommand("profile", function(text)
        local args = string.split(text, " ")
        if #args > 1 then
            if args[2] == "start" then
                debug.profiStart()
            elseif args[2] == "stop" then
                debug.profiStop()
            end
        end
    end)

    app:addCommand("/gift", function(text)
        local ary = string.split(text, " ")
        if #ary > 1 then
            print("===========+>>> ", ary[2] )
            app.channelAPI:reqGiftCode(ary[2], function()
                display.pushToast(L("礼包码测试成功")) --@ignore
            end)
           
        end
    end)


    app:addCommand("adreport", function(text)
        -- 1 firebase 2 facebook 3 appsflyer 4 adjust
        -- Google Facebook  AppsFlyer Adjust
        app.channelAPI:ADReport({
            event = "active",
            params = {
                account = app.channelAPI:getAccount(),
                server = tostring(app.session:getZoneId()),
                rolename = UD.player.name,
                role_id = UD.player.uid,
                level = "10",
                active = "mde4k4",
            },
            channels = {
                1,2,3,4
            }

        })
    end)

    app:addCommand("pwrdtrackevent", function(text)
        local ary = string.split(text, " ")
        dump(ary, "Command pwrdtrackevent")
        if #ary > 1 then
             local list = {eventName = ary[2], type = tonumber(ary[3])}
             app.pwrdTrackEvent:addTrackEvent(list)
        end
    end)

    app:addCommand("advert", function(text)
        local ary = string.split(text, " ")
        if #ary > 1 then
            local config = GD:getActivityOpenBySubType(tonumber(ary[2]))
            if config then
                app:sendMsg("RewardController", "openAdvert", config)
            end
        end
    end)

    app:addCommand("httpdns", function(text)
        local ary =  string.split(text, " ")
        dump(ary, "Command httpdns")
        if #ary > 1 then
            local dns = ary[2]
            if dns then
                app.channelAPI:getHostByNameAsync(dns, function(ips)
                    dump(ips, "Command Callbackips")
                end)
            end
        end
    end)

    app:addCommand("clearchat", function(text)
        local ary = string.split(text, " ")
        if #ary > 1 then
            local uid = tonumber(ary[2])
            if uid then
                app:sendMsg("IMModel", "onClearMessage", uid)
            end
        end
    end)

    app:addCommand("starreview", function()
        app.channelAPI:showStarReview()
    end)

    -- 跨服工会战
    app:addCommand("guildwar", function(text)
        UIHandler:handleMessage({id = Constant.FUNC_TYPE_CS_GUILD_WAR,mode = "open"})
    end)
end